<template>
    <div class="page-container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="分类名称" prop="categoryName">
          <el-input
            v-model="queryParams.categoryName"
            placeholder="请输入分类名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="分类状态" clearable>
            <el-option label="启用" :value="0" />
            <el-option label="禁用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['commodity:category:add']"
            >新增分类</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['commodity:category:remove']"
            >批量删除</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
          :columns="columns"
        ></right-toolbar>
      </el-row>
  
      <el-table
        v-loading="loading"
        :data="categoryList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="ID"
          align="center"
          key="id"
          prop="id"
          v-if="columns[0].visible"
        />
        <el-table-column
          label="分类名称"
          align="center"
          key="categoryName"
          prop="categoryName"
          v-if="columns[1].visible"
        />
        <el-table-column
          label="商品数量"
          align="center"
          key="productCount"
          prop="productCount"
          v-if="columns[2].visible"
        />
        <el-table-column
          label="排序"
          align="center"
          key="sortOrder"
          prop="sortOrder"
          v-if="columns[3].visible"
        />
        <el-table-column
          label="状态"
          align="center"
          key="status"
          prop="status"
          v-if="columns[4].visible"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
              {{ scope.row.status === 0 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          key="createdAt"
          prop="createdAt"
          v-if="columns[5].visible"
        />
        <el-table-column
          label="操作"
          align="center"
          width="180"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['commodity:category:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['commodity:category:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改分类对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
          </el-form-item>
          <el-form-item label="商品数量" prop="productCount">
            <el-input-number v-model="form.productCount" :min="0" :max="999" />
          </el-form-item>
          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="form.sortOrder" :min="0" :max="999" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import {
    listCategories,
    getCategory,
    addCategory,
    updateCategory,
    deleteCategory,
    deleteCategories,
  } from "@/api/commodity/category";
  
  export default {
    name: "ProductCategory",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 分类列表数据
        categoryList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          categoryName: undefined,
          status: undefined,
        },
        // 列信息
        columns: [
          { key: 0, label: `ID`, visible: true },
          { key: 1, label: `分类名称`, visible: true },
          { key: 2, label: `商品数量`, visible: true },
          { key: 3, label: `排序`, visible: true },
          { key: 4, label: `状态`, visible: true },
          { key: 5, label: `创建时间`, visible: true },
        ],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          id: undefined,
          categoryName: undefined,
          productCount: 0,
          sortOrder: 0,
          status: 0,
        },
        // 表单校验
        rules: {
          categoryName: [
            { required: true, message: "分类名称不能为空", trigger: "blur" },
            { min: 2, max: 50, message: "分类名称长度必须在2到50个字符之间", trigger: "blur" }
          ],
          productCount: [
            { required: true, message: "商品数量不能为空", trigger: "change" },
            { type: 'number', message: "商品数量必须为数字", trigger: "change" },
            // { min: 0, message: "商品数量不能为负数", trigger: "change" }
          ],
          sortOrder: [
            { required: true, message: "排序不能为空", trigger: "blur" }
          ],
          status: [
            { required: true, message: "状态不能为空", trigger: "change" }
          ]
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询分类列表 */
      getList() {
        this.loading = true;
        listCategories(this.queryParams)
          .then((response) => {
            this.categoryList = response.data || [];
            this.total = Number(response.total) || 0;
          })
          .catch(() => {
            this.$modal.msgError("获取分类列表失败");
            this.categoryList = [];
            this.total = 0;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加分类";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids[0];
        if (!id) {
          this.$modal.msgError("获取分类ID失败");
          return;
        }
        getCategory(id).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改分类";
        }).catch((error) => {
          this.$modal.msgError(error.msg || "获取分类信息失败");
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id) {
              updateCategory(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCategory(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const categoryIds = row.id || this.ids;
        this.$modal
          .confirm("是否确认删除选中的分类数据？")
          .then(() => {
            if (row.id) {
              return deleteCategory(row.id);
            } else {
              return deleteCategories(this.ids.join(","));
            }
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      },
      /** 取消按钮 */
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          categoryName: undefined,
          productCount: 0,
          sortOrder: 0,
          status: 0,
        };
        this.resetForm("form");
      },
    },
  };
  </script>
  
  <style>
  .page-container {
    margin-top: 20px;
    padding: 0 20px;
  }
  
  .mb8 {
    margin-bottom: 8px;
  }
  
  .el-table .cell {
    white-space: nowrap;
  }
  
  .el-form-item__label {
    font-weight: bold;
  }
  
  .el-dialog__body {
    padding: 20px 30px;
  }
  </style>
  